using AutoMapper;
using B.S.BaseData.Api.Write.Applicantion.Command.HospitalTwoCommand;
using B.S.BaseData.Api.Write.GetCelim;
using B.S.BaseData.ErrorCode;
using B.S.BaseData.Infrastructure.Interface;
using B.S.BataBase.Domain.Hosp;
using MediatR;
using Microsoft.EntityFrameworkCore;
using Yitter.IdGenerator;

namespace B.S.BaseData.Api.Write.Applicantion.CommandHandler.HospitalTwoCommandHandler
{
    public class HospitalAddCommandHandler : IRequestHandler<HospitalAddCommand, APIResult<int>>
    {
        private readonly IBaseRepository<Hospital> _repository;
        private readonly IMapper _mapper;
        private readonly IIdContextCemil _idContext;
        public HospitalAddCommandHandler(IBaseRepository<Hospital> repository, IMapper mapper, IIdContextCemil idContext)
        {
            _repository = repository;
            _mapper = mapper;
            _idContext = idContext;
        }

        public async Task<APIResult<int>> Handle(HospitalAddCommand request, CancellationToken cancellationToken)
        {
            var result = new APIResult<int>();

            try
            {
                var list = _mapper.Map<Hospital>(request);
                list.Id = YitIdHelper.NextId();
                list.CreateName = _idContext.UserName;
                list.Uploader = _idContext.UserName;
                result.Data = await _repository.CreateAsync(list);
                result.Code = ApiEnum.Success;
                result.Msg = "医院添加成功";
                return await Task.FromResult(result);
            }
            catch (Exception ex)
            {
                result.Code = ApiEnum.Fail;
                result.Msg = $"添加医院失败：{ex.Message}";
                return await Task.FromResult(result);
            }
        }
    }
}